package cn.zhangfusheng.elasticsearch.template;

import cn.zhangfusheng.elasticsearch.util.JsonConstant;
import com.alibaba.fastjson2.JSON;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.index.reindex.UpdateByQueryRequest;
import org.elasticsearch.search.builder.SearchSourceBuilder;

import java.util.Map;

/**
 * es操作的日志格式化处理
 * @author zhangfusheng
 * @date 2023/12/25
 */
interface TemplateLogFormat {


    default String formatDsl(IndexRequest request) {
        String index = request.index(), routing = request.routing(), id = request.id();
        Map<String, Object> source = request.sourceAsMap();
        String dsl = index + "/_doc";
        if (StringUtils.isNotBlank(id)) dsl += "/" + id;
        if (StringUtils.isNotBlank(routing)) dsl += "?routing=" + routing;
        return dsl + " " + JSON.toJSONString(source, JsonConstant.DEFAULT_WRITE_CONTEXT);
    }

    default String formatDsl(GetRequest request) {
        String index = request.index(), routing = request.routing(), id = request.id();
        String dsl = index + "/_search?q=_id:" + id;
        if (StringUtils.isNotBlank(routing)) dsl += "&routing=" + routing;
        return dsl;
    }

    default String formatDsl(UpdateRequest request) {
        IndexRequest indexRequest = request.doc();
        Map<String, Object> source = indexRequest.sourceAsMap();
        String index = request.index(), routing = request.routing(), id = request.id();
        String dsl = index + "/_doc/" + id;
        if (StringUtils.isNotBlank(routing)) dsl += "?routing=" + routing;
        return dsl + " " + JSON.toJSONString(source, JsonConstant.DEFAULT_WRITE_CONTEXT);
    }

    default String formatDsl(BulkRequest request) {
        return request.toString();
    }

    default String formatDsl(UpdateByQueryRequest request) {
        String[] index = request.indices();
        String routing = request.getRouting();
        SearchSourceBuilder searchSourceBuilder = request.getSearchRequest().source();
        return StringUtils.isBlank(routing)
                ? StringUtils.join(index, ",") + "/_update_by_query " + searchSourceBuilder.toString()
                : StringUtils.join(index, ",") + "/_update_by_query?routing=" + routing + " " + searchSourceBuilder.toString();
    }

    default String formatDsl(DeleteRequest request) {
        String index = request.index(), routing = request.routing(), id = request.id();
        String dsl = index + "/_doc";
        if (StringUtils.isNotBlank(id)) dsl += "/" + id;
        if (StringUtils.isNotBlank(routing)) dsl += "?routing=" + routing;
        return dsl;
    }

}
